package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code65FindFirstAndLastPositionOfElementInSortedArray {

    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        int l = 0;
        int r = nums.length - 1;
        int mid;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            if (nums[mid] >= target) {
                if (nums[mid] == target && (mid == 0 || nums[mid - 1] != target)) {
                    res[0] = mid;
                    break;
                }
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        l = 0;
        r = nums.length - 1;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            if (nums[mid] <= target) {
                if (nums[mid] == target && (mid == nums.length - 1 || nums[mid + 1] != target)) {
                    res[1] = mid;
                    break;
                }
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return res;
    }
}
